package com.Final.hj;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Socket_Add extends AppCompatActivity implements View.OnClickListener {
    private ImageView frined_a_back;
    private TextView friend_seach, title_dlg;
    private EditText friend_seach_ed, setLetter;
    private Button rejectBtn, solvBbtn;



    private String seach_name, letter_name;

    private static final int SEACH_FRIEND = 1;
    private int SEACH_FRIEND_ERR = 0;

    //创建适配器
    private SeachFriendAdapter adapter;
    //适配器的数据
    private List<SeachFriedList> seach_list = new ArrayList<>();
    private Context seachFContext;
    private ListView seachListView;

    private SeachFriedList seachFriendItem;
    //数据库信息
    private SQLSavaInfo sqlData;


    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.add_friend);
        initView();
        seachFContext = this;

        //点击每一项
        seachListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //弹窗显示添加好友
                addDlg(position);
            }
        });
    }

    public void addDlg(int num){
        //获取点击实例
        seachFriendItem = seach_list.get(num);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.add_page, null);

        //设置页面
        builder.setView(view);

        final AlertDialog dlg = builder.create();
        //初始化相应的内容
        initSelectView(view);

        //确认
        solvBbtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                //发送请求
                sendAddF(dlg);
            }
        });

        //点击取消
        rejectBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                dlg.cancel();
            }
        });

        dlg.show();
    }


    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.friend_add_back:
                this.finish();
                break;
            case R.id.friend_seach:
                friendSeach();
                break;
        }
    }

    public void friendSeach(){
        //此时这里需要发送请求

        //获取输入框的值
        seach_name = friend_seach_ed.getText().toString().trim();
        if(TextUtils.isEmpty(seach_name)){
            Toast.makeText(this, "搜索用户名不能为空", Toast.LENGTH_LONG).show();
            return;
        }


        //启动线程 发送请求
        new Thread(new Runnable() {

            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/sfriend?uname="+ seach_name)
                            .build();

                    //这里发送同步请求即可
                    Response response = client.newCall(request).execute();

                    String string = response.body().string();


                    System.out.print("得到数据");
                    //解析数据
                    parseData(string);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void parseData(String strJson) {
        //清空集合
        seach_list.clear();
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(strJson).getAsJsonArray();
        Gson gson = new Gson();

        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            SeachFriedList userBean = gson.fromJson(user, SeachFriedList.class);
            seach_list.add(userBean);
        }

        //此时发送msg 更新ui
        Message message = new Message();
        message.what = SEACH_FRIEND;
        handler.sendMessage(message);
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what){
                case SEACH_FRIEND:
                    adapter = new SeachFriendAdapter(seachFContext, R.layout.seach_friend_adapter, seach_list);
                    seachListView.setAdapter(adapter);
                    break;
            }
        }
    };

    //初始化变量
    public void initView(){
        frined_a_back = (ImageView) findViewById(R.id.friend_add_back);
        friend_seach = (TextView) findViewById(R.id.friend_seach);
        friend_seach_ed = (EditText) findViewById(R.id.friend_seach_ed);
        seachListView = (ListView) findViewById(R.id.seach_friend_list);

        frined_a_back.setOnClickListener(this);
        friend_seach.setOnClickListener(this);
    }
    //弹窗
    public void initSelectView(View v){
        rejectBtn = (Button) v.findViewById(R.id.add_reject);
        solvBbtn = (Button) v.findViewById(R.id.add_solve);
        title_dlg = (TextView) v.findViewById(R.id.setTitle);
        setLetter = (EditText) v.findViewById(R.id.add_edit);
    }

    //发送添加好友请求
    public void sendAddF(final AlertDialog dlg){

        letter_name = setLetter.getText().toString().trim();
        if(letter_name.isEmpty()){
            Toast.makeText(Socket_Add.this, "请输入对方备注", Toast.LENGTH_SHORT).show();
            return;
        }else{
            //关闭对话框
            dlg.dismiss();
        }

        sqlData = LoginSQLManger.getInstance(seachFContext).queryAll();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();

                    RequestBody requestBody = new FormBody.Builder()
                            .add("uname", letter_name)
                            .add("hImgId", seachFriendItem.getHImgId())
                            .add("id", seachFriendItem.get_id())
                            .add("myUname", sqlData.getUname())
                            .add("myHImgId", sqlData.gethImgId())
                            .add("myId", sqlData.getMyId())
                            .add("status", "1")
                            .build();

                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/afriend")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String string = response.body().string();

                    handleAF(string);
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("异常");
                }
            }
        }).start();
    }


    public void handleAF(String str){

        Looper.prepare();
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        Looper.loop();

        //在这里发送请求获取最新的数据
    }
}
